<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="习惯名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入习惯名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="今日是否打卡" prop="isClockToday" label-width="120px">
        <el-select v-model="queryParams.isClockToday" placeholder="打卡状态" clearable>
          <el-option
            v-for="dict in dict.type.is_clock_today"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['habit:habit:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['habit:habit:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['habit:habit:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['habit:habit:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['habit:habit:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="habitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="习惯名称" align="center" prop="name"/>
      <el-table-column label="用户id" align="center" prop="uid"/>
      <el-table-column prop="iconUrl" label="习惯头像" min-width="70%">
        <!-- 图片的显示 -->
        <template slot-scope="scope">
          <img :src="scope.row.iconUrl" min-width="70" height="70"/>
        </template>
      </el-table-column>
      <el-table-column label="总打卡天数" align="center" prop="totalDays"/>
      <el-table-column label="当前连续" align="center" prop="currentContinue"/>
      <el-table-column label="最高连续" align="center" prop="mostContinue"/>
      <el-table-column label="今日是否打卡" align="center" prop="isClockToday">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_clock_today" :value="scope.row.isClockToday"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['habit:habit:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['habit:habit:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[5,10, 20]"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改习惯对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="习惯名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入习惯名称" clearable/>
        </el-form-item>
        <el-form-item label="图片url" prop="iconUrl">
          <el-input v-model="form.iconUrl" placeholder="请输入图片url" clearable/>
        </el-form-item>
        <el-form-item label="用户id" prop="uid" clearable>
          <el-input-number v-model="form.uid" controls-position="right" :min="1"/>
        </el-form-item>
        <el-form-item label="总打卡天数" prop="totalDays" clearable>
          <el-input-number v-model="form.totalDays" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="当前连续天数" prop="currentContinue" clearable>
          <el-input-number v-model="form.currentContinue" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="最高连续天数" prop="mostContinue" clearable>
          <el-input-number v-model="form.mostContinue" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="今日是否打卡" prop="isClockToday">
          <el-select v-model="form.isClockToday" placeholder="打卡状态" clearable>
            <el-option
              v-for="dict in dict.type.is_clock_today"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--批量上传对话框-->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateFlag=' + upload.updateFlag"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateFlag"/>
          是否更新已经存在的数据
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="importTemplate">下载模板</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="submitCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryHabitList,
  addHabit,
  updateHabit,
  getOne,
  removeHabit,
  exportTemplate
} from "@/api/habit/habit";
import {getToken} from "@/utils/auth";

export default {
  name: "Post",
  dicts: ['is_clock_today'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 习惯表格数据
      habitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        name: undefined,
        isClockToday: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        iconUrl: undefined,
        uid: 1,
        totalDays: 0,
        currentContinue: 0,
        mostContinue: 0,
        isClockToday: undefined
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "习惯名称不能为空", trigger: "blur"}
        ]
      },
      //批量导入
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateFlag: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/web/habit/import"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询习惯列表 */
    getList() {
      this.loading = true;
      queryHabitList(this.queryParams).then(response => {
        this.total = response.data.total
        this.habitList = response.data.list
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加习惯";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      var handelId = null
      //选择框
      if (row.id === undefined || row.id === null) {
        handelId = this.ids[0]
      }else {
        handelId = row.id
      }
      //回显请求
      getOne(handelId).then(response => {
        this.form = response.data
      })
      this.title = "修改习惯";
      this.open = true;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateHabit(this.form).then(response => {
              if (response.code === 0) {
                this.$modal.msgSuccess("修改成功");
              }else {
                this.$modal.msgSuccess("修改失败");
              }
              this.open = false;
              this.getList();
            });
          } else {
            addHabit(this.form).then(response => {
              console.log("新增返回",response)
              if (response.code === 0) {
                this.$modal.msgSuccess("新增成功");
              }else {
                this.$modal.msgSuccess("新增失败");
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认编号为"' + ids + '"的数据项？').then(function () {
        return removeHabit(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('web/habit/export', {
        ...this.queryParams
      }, `习惯列表_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "习惯信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      exportTemplate().then(response => {
        console.log("ssss",response.msg)
        //this.download(response.msg);
        this.download('web/habit/exportTemplate', {}, `导入模板_${new Date().getTime()}.xlsx`)
      });
    },
    submitFileForm() {//提交
      this.$refs.upload.submit();
      this.upload.isUploading = false;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;//禁用上传
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.updateFlag = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "习惯信息导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    submitCancel() {//取消提交
      this.$refs.upload.clearFiles();
      this.upload.updateFlag = false;
      this.upload.open = false;
    }
  }
};
</script>
